import { HttpException, HttpStatus, Injectable, UnauthorizedException } from "@nestjs/common";
import { JwtService } from "./jwt.service";
import { UserEntity } from "../User/User.entity";
import { UserService } from "../User/User.service";
@Injectable()
export class AuthService {

    constructor(private readonly userService: UserService,
        private readonly jwtService: JwtService,
    ) { }

    async createToken(user: UserEntity) {
        delete user.userPassword;
        return {
            user,
            expiresIn: user ? 1 : process.env.JWT_EXPIRATION_TIME || 3600,
            accessToken: user ? await this.jwtService.sign(user) : undefined
        }
    }

    async validateUserByName(payload: any): Promise<any> {
        if (payload?.userName) {
            const user = await this.userService.findOneByName(
                payload.userName
            );
            console.log("user", user)
            if (!user) {
                throw new UnauthorizedException('Incorrect username or password');
            }
            return user;
        }
        return undefined
    }


}